<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>票务管理 - 列车车次管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../css/admin.css" rel="stylesheet">
</head>
<body>
    <!-- 导航栏 -->    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="/admin/dashboard.html">
                <img src="/images/logo.jpeg" alt="Logo" class="admin-logo d-inline-block align-text-top">
                <i class="fas fa-train me-2"></i>列车车次管理系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/dashboard.html">
                            <i class="fas fa-tachometer-alt me-1"></i>仪表盘
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/users.html">
                            <i class="fas fa-users me-1"></i>用户管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/stations.html">
                            <i class="fas fa-map-marker-alt me-1"></i>车站管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/trains.html">
                            <i class="fas fa-train me-1"></i>火车管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/routes.html">
                            <i class="fas fa-route me-1"></i>线路管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/schedules.html">
                            <i class="fas fa-calendar-alt me-1"></i>班次管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/admin/tickets.html">
                            <i class="fas fa-ticket-alt me-1"></i>票务管理
                        </a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user me-1"></i><span id="adminName">管理员</span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/profile.html">个人资料</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" onclick="logout()">退出登录</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <!-- 页面标题 -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2><i class="fas fa-ticket-alt me-2"></i>票务管理</h2>
                    <div>
                        <button class="btn btn-info" onclick="loadTicketsStatistics()">
                            <i class="fas fa-chart-bar me-1"></i>统计报表
                        </button>
                        <button class="btn btn-success" onclick="exportToCSV()">
                            <i class="fas fa-download me-1"></i>导出数据
                        </button>
                    </div>
                </div>

                <!-- 统计卡片 -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card bg-primary text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h6 class="card-title">总票数</h6>
                                        <h3 id="totalTickets">-</h3>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-ticket-alt fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-success text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h6 class="card-title">已支付</h6>
                                        <h3 id="paidTickets">-</h3>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-check-circle fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-warning text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h6 class="card-title">待支付</h6>
                                        <h3 id="pendingTickets">-</h3>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-clock fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-secondary text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h6 class="card-title">总收入</h6>
                                        <h3 id="totalRevenue">¥-</h3>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-dollar-sign fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 搜索和过滤器 -->
                <div class="card mb-4">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-2">
                                <label for="searchTicketNumber" class="form-label">票号</label>
                                <input type="text" class="form-control" id="searchTicketNumber" placeholder="输入票号">
                            </div>
                            <div class="col-md-2">
                                <label for="searchUserName" class="form-label">乘客姓名</label>
                                <input type="text" class="form-control" id="searchUserName" placeholder="输入姓名">
                            </div>
                            <div class="col-md-2">
                                <label for="searchTrainNumber" class="form-label">车次号</label>
                                <input type="text" class="form-control" id="searchTrainNumber" placeholder="输入车次号">
                            </div>
                            <div class="col-md-2">
                                <label for="filterSeatType" class="form-label">座位类型</label>
                                <select class="form-select" id="filterSeatType">
                                    <option value="">全部类型</option>
                                    <option value="硬座">硬座</option>
                                    <option value="软座">软座</option>
                                    <option value="硬卧">硬卧</option>
                                    <option value="软卧">软卧</option>
                                    <option value="商务座">商务座</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="filterStatus" class="form-label">状态</label>
                                <select class="form-select" id="filterStatus">
                                    <option value="">全部状态</option>
                                    <option value="已支付">已支付</option>
                                    <option value="待支付">待支付</option>
                                    <option value="已取消">已取消</option>
                                    <option value="已退款">已退款</option>
                                </select>
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button class="btn btn-primary me-2" onclick="searchTickets()">
                                    <i class="fas fa-search me-1"></i>搜索
                                </button>
                                <button class="btn btn-secondary" onclick="resetFilters()">
                                    <i class="fas fa-undo me-1"></i>重置
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 票务列表 -->
                <div class="card">
                    <div class="card-body">
                        <div id="loadingSpinner" class="text-center" style="display: none;">
                            <div class="spinner-border" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead class="table-dark">
                                    <tr>
                                        <th>票号</th>
                                        <th>乘客信息</th>
                                        <th>车次信息</th>
                                        <th>座位信息</th>
                                        <th>价格</th>
                                        <th>购票时间</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="ticketsTableBody">
                                    <!-- 数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 分页 -->
                        <nav aria-label="分页导航">
                            <ul class="pagination justify-content-center" id="pagination">
                                <!-- 分页按钮将通过JavaScript动态生成 -->
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 票务详情模态框 -->
    <div class="modal fade" id="ticketDetailModal" tabindex="-1" aria-labelledby="ticketDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="ticketDetailModalLabel">票务详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="ticketDetailContent">
                    <!-- 详情内容将通过JavaScript动态生成 -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="printTicketBtn" onclick="printTicket()">
                        <i class="fas fa-print me-1"></i>打印票据
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 状态更新模态框 -->
    <div class="modal fade" id="statusModal" tabindex="-1" aria-labelledby="statusModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="statusModalLabel">更新票务状态</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="statusForm">
                        <input type="hidden" id="statusTicketId">
                        <div class="mb-3">
                            <label for="newStatus" class="form-label">新状态</label>
                            <select class="form-select" id="newStatus" required>
                                <option value="">请选择状态</option>
                                <option value="已支付">已支付</option>
                                <option value="待支付">待支付</option>
                                <option value="已取消">已取消</option>
                                <option value="已退款">已退款</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="statusReason" class="form-label">原因说明</label>
                            <textarea class="form-control" id="statusReason" rows="3" placeholder="请输入状态变更的原因"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateTicketStatus()">
                        <i class="fas fa-save me-1"></i>确认更新
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 退款确认模态框 -->
    <div class="modal fade" id="refundModal" tabindex="-1" aria-labelledby="refundModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="refundModalLabel">确认退款</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>您确定要为票号 <strong id="refundTicketNumber"></strong> 办理退款吗？</p>
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        退款金额：<strong id="refundAmount">¥0.00</strong><br>
                        此操作不可撤销，请确认无误后操作。
                    </div>
                    <div class="mb-3">
                        <label for="refundReason" class="form-label">退款原因</label>
                        <textarea class="form-control" id="refundReason" rows="3" placeholder="请输入退款原因"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" onclick="confirmRefund()">
                        <i class="fas fa-money-bill-wave me-1"></i>确认退款
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../js/admin.js"></script>
    <script>
        let currentPage = 1;
        let totalPages = 1;
        let currentTicketId = null;

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAdminAuth();
            loadTicketsStatistics();
            loadTickets();
        });

        // 加载票务统计
        async function loadTicketsStatistics() {
            try {
                const response = await fetch('/api/tickets/statistics', {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('加载统计数据失败');
                }
                
                const stats = await response.json();
                
                document.getElementById('totalTickets').textContent = stats.total || 0;
                document.getElementById('paidTickets').textContent = stats.paid || 0;
                document.getElementById('pendingTickets').textContent = stats.pending || 0;
                document.getElementById('totalRevenue').textContent = `¥${(stats.revenue || 0).toFixed(2)}`;
                
            } catch (error) {
                console.error('加载统计数据失败:', error);
                // 设置默认值
                document.getElementById('totalTickets').textContent = '0';
                document.getElementById('paidTickets').textContent = '0';
                document.getElementById('pendingTickets').textContent = '0';
                document.getElementById('totalRevenue').textContent = '¥0.00';
            }
        }

        // 加载票务列表
        async function loadTickets(page = 1) {
            try {
                showLoading(true);
                const searchTicketNumber = document.getElementById('searchTicketNumber').value;
                const searchUserName = document.getElementById('searchUserName').value;
                const searchTrainNumber = document.getElementById('searchTrainNumber').value;
                const filterSeatType = document.getElementById('filterSeatType').value;
                const filterStatus = document.getElementById('filterStatus').value;

                let url = `/api/tickets?page=${page - 1}&size=10`;
                
                if (searchTicketNumber) {
                    url += `&ticketNumber=${encodeURIComponent(searchTicketNumber)}`;
                }
                if (searchUserName) {
                    url += `&userName=${encodeURIComponent(searchUserName)}`;
                }
                if (searchTrainNumber) {
                    url += `&trainNumber=${encodeURIComponent(searchTrainNumber)}`;
                }
                if (filterSeatType) {
                    url += `&seatType=${encodeURIComponent(filterSeatType)}`;
                }
                if (filterStatus) {
                    url += `&status=${encodeURIComponent(filterStatus)}`;
                }

                const response = await fetch(url, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('加载票务列表失败');
                }
                
                const data = await response.json();
                displayTickets(data.content || data);
                
                if (data.totalPages) {
                    totalPages = data.totalPages;
                    currentPage = page;
                    updatePagination();
                }
            } catch (error) {
                console.error('加载票务列表失败:', error);
                showAlert('加载票务列表失败', 'danger');
            } finally {
                showLoading(false);
            }
        }

        // 显示票务列表
        function displayTickets(tickets) {
            const tbody = document.getElementById('ticketsTableBody');
            
            if (!tickets || tickets.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="text-center">暂无数据</td></tr>';
                return;
            }

            tbody.innerHTML = tickets.map(ticket => `
                <tr>
                    <td>
                        <strong>${ticket.ticketNumber}</strong>
                        <br>
                        <small class="text-muted">
                            <a href="#" onclick="showTicketDetail(${ticket.id})" class="text-decoration-none">
                                <i class="fas fa-info-circle me-1"></i>查看详情
                            </a>
                        </small>
                    </td>
                    <td>
                        <strong>${ticket.passengerName}</strong><br>
                        <small class="text-muted">${ticket.passengerIdCard}</small><br>
                        <small class="text-muted">${ticket.passengerPhone || ''}</small>
                    </td>
                    <td>
                        <strong>${ticket.trainNumber}</strong><br>
                        <small class="text-muted">${ticket.departureStation} → ${ticket.arrivalStation}</small><br>
                        <small class="text-muted">${formatDateTime(ticket.departureTime)}</small>
                    </td>
                    <td>
                        <span class="badge bg-info">${ticket.seatType}</span><br>
                        <small class="text-muted">${ticket.seatNumber || '未分配'}</small>
                    </td>
                    <td><strong>¥${ticket.price}</strong></td>
                    <td>${formatDateTime(ticket.bookingTime)}</td>
                    <td><span class="badge ${getStatusBadgeClass(ticket.status)}">${ticket.status}</span></td>
                    <td>
                        <div class="btn-group-vertical btn-group-sm">
                            <button class="btn btn-outline-primary" onclick="showStatusModal(${ticket.id}, '${ticket.status}')" title="更新状态">
                                <i class="fas fa-edit"></i>
                            </button>
                            ${ticket.status === '已支付' ? 
                                `<button class="btn btn-outline-warning" onclick="showRefundModal(${ticket.id}, '${ticket.ticketNumber}', ${ticket.price})" title="退款">
                                    <i class="fas fa-money-bill-wave"></i>
                                </button>` : ''
                            }
                        </div>
                    </td>
                </tr>
            `).join('');
        }

        // 获取状态徽章样式
        function getStatusBadgeClass(status) {
            switch (status) {
                case '已支付': return 'bg-success';
                case '待支付': return 'bg-warning';
                case '已取消': return 'bg-secondary';
                case '已退款': return 'bg-danger';
                default: return 'bg-secondary';
            }
        }

        // 显示票务详情
        async function showTicketDetail(ticketId) {
            try {
                const response = await fetch(`/api/tickets/${ticketId}`, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('获取票务详情失败');
                }
                
                const ticket = await response.json();
                currentTicketId = ticketId;
                
                const content = `
                    <div class="row">
                        <div class="col-md-6">
                            <h6>票务信息</h6>
                            <table class="table table-sm">
                                <tr><td>票号</td><td>${ticket.ticketNumber}</td></tr>
                                <tr><td>车次</td><td>${ticket.trainNumber}</td></tr>
                                <tr><td>出发站</td><td>${ticket.departureStation}</td></tr>
                                <tr><td>到达站</td><td>${ticket.arrivalStation}</td></tr>
                                <tr><td>出发时间</td><td>${formatDateTime(ticket.departureTime)}</td></tr>
                                <tr><td>到达时间</td><td>${formatDateTime(ticket.arrivalTime)}</td></tr>
                                <tr><td>座位类型</td><td>${ticket.seatType}</td></tr>
                                <tr><td>座位号</td><td>${ticket.seatNumber || '未分配'}</td></tr>
                                <tr><td>价格</td><td><strong>¥${ticket.price}</strong></td></tr>
                                <tr><td>状态</td><td><span class="badge ${getStatusBadgeClass(ticket.status)}">${ticket.status}</span></td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6>乘客信息</h6>
                            <table class="table table-sm">
                                <tr><td>姓名</td><td>${ticket.passengerName}</td></tr>
                                <tr><td>身份证号</td><td>${ticket.passengerIdCard}</td></tr>
                                <tr><td>手机号</td><td>${ticket.passengerPhone || '未提供'}</td></tr>
                                <tr><td>购票时间</td><td>${formatDateTime(ticket.bookingTime)}</td></tr>
                                <tr><td>支付时间</td><td>${ticket.paymentTime ? formatDateTime(ticket.paymentTime) : '未支付'}</td></tr>
                                <tr><td>退款时间</td><td>${ticket.refundTime ? formatDateTime(ticket.refundTime) : '-'}</td></tr>
                            </table>
                            
                            ${ticket.statusHistory && ticket.statusHistory.length > 0 ? `
                                <h6 class="mt-3">状态历史</h6>
                                <div class="timeline">
                                    ${ticket.statusHistory.map(history => `
                                        <div class="timeline-item">
                                            <small class="text-muted">${formatDateTime(history.timestamp)}</small><br>
                                            <span class="badge ${getStatusBadgeClass(history.status)}">${history.status}</span>
                                            ${history.reason ? `<br><small>${history.reason}</small>` : ''}
                                        </div>
                                    `).join('')}
                                </div>
                            ` : ''}
                        </div>
                    </div>
                `;
                
                document.getElementById('ticketDetailContent').innerHTML = content;
                new bootstrap.Modal(document.getElementById('ticketDetailModal')).show();
            } catch (error) {
                console.error('获取票务详情失败:', error);
                showAlert('获取票务详情失败', 'danger');
            }
        }

        // 显示状态更新模态框
        function showStatusModal(ticketId, currentStatus) {
            document.getElementById('statusTicketId').value = ticketId;
            document.getElementById('newStatus').value = currentStatus;
            document.getElementById('statusReason').value = '';
            new bootstrap.Modal(document.getElementById('statusModal')).show();
        }

        // 更新票务状态
        async function updateTicketStatus() {
            try {
                const ticketId = document.getElementById('statusTicketId').value;
                const newStatus = document.getElementById('newStatus').value;
                const reason = document.getElementById('statusReason').value;

                if (!newStatus) {
                    showAlert('请选择新状态', 'warning');
                    return;
                }

                const response = await fetch(`/api/tickets/${ticketId}/status`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    },
                    body: JSON.stringify({
                        status: newStatus,
                        reason: reason
                    })
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '状态更新失败');
                }

                showAlert('票务状态更新成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('statusModal')).hide();
                loadTickets(currentPage);
                loadTicketsStatistics();
            } catch (error) {
                console.error('更新票务状态失败:', error);
                showAlert(error.message || '更新票务状态失败', 'danger');
            }
        }

        // 显示退款模态框
        function showRefundModal(ticketId, ticketNumber, price) {
            currentTicketId = ticketId;
            document.getElementById('refundTicketNumber').textContent = ticketNumber;
            document.getElementById('refundAmount').textContent = `¥${price}`;
            document.getElementById('refundReason').value = '';
            new bootstrap.Modal(document.getElementById('refundModal')).show();
        }

        // 确认退款
        async function confirmRefund() {
            try {
                const reason = document.getElementById('refundReason').value;

                if (!reason.trim()) {
                    showAlert('请输入退款原因', 'warning');
                    return;
                }

                const response = await fetch(`/api/tickets/${currentTicketId}/refund`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    },
                    body: JSON.stringify({
                        reason: reason
                    })
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '退款失败');
                }

                showAlert('退款处理成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('refundModal')).hide();
                loadTickets(currentPage);
                loadTicketsStatistics();
            } catch (error) {
                console.error('退款处理失败:', error);
                showAlert(error.message || '退款处理失败', 'danger');
            }
        }

        // 打印票据
        function printTicket() {
            if (!currentTicketId) return;
            
            // 创建打印窗口
            const printWindow = window.open('', '_blank');
            const ticketContent = document.getElementById('ticketDetailContent').innerHTML;
            
            printWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>火车票</title>
                    <style>
                        body { font-family: Arial, sans-serif; padding: 20px; }
                        .ticket { border: 2px solid #000; padding: 20px; max-width: 600px; margin: 0 auto; }
                        table { width: 100%; border-collapse: collapse; }
                        td { padding: 5px; border-bottom: 1px solid #ddd; }
                        .header { text-align: center; font-size: 24px; font-weight: bold; margin-bottom: 20px; }
                        @media print { .no-print { display: none; } }
                    </style>
                </head>
                <body>
                    <div class="ticket">
                        <div class="header">中国铁路车票</div>
                        ${ticketContent}
                    </div>
                    <script>
                        window.onload = function() { window.print(); window.close(); }
                    </script>
                </body>
                </html>
            `);
            
            printWindow.document.close();
        }

        // 搜索票务
        function searchTickets() {
            currentPage = 1;
            loadTickets();
        }

        // 重置过滤器
        function resetFilters() {
            document.getElementById('searchTicketNumber').value = '';
            document.getElementById('searchUserName').value = '';
            document.getElementById('searchTrainNumber').value = '';
            document.getElementById('filterSeatType').value = '';
            document.getElementById('filterStatus').value = '';
            currentPage = 1;
            loadTickets();
        }

        // 导出到CSV
        function exportToCSV() {
            const csvContent = generateCSVContent();
            downloadCSV(csvContent, 'tickets.csv');
        }

        function generateCSVContent() {
            const headers = ['票号', '乘客姓名', '身份证号', '车次号', '出发站', '到达站', '座位类型', '座位号', '价格', '购票时间', '状态'];
            let csv = headers.join(',') + '\n';
            
            const rows = document.querySelectorAll('#ticketsTableBody tr');
            rows.forEach(row => {
                const cells = row.querySelectorAll('td');
                if (cells.length > 1) {
                    const ticketNumber = cells[0].textContent.trim().split('\n')[0];
                    const passengerInfo = cells[1].textContent.trim().split('\n');
                    const trainInfo = cells[2].textContent.trim().split('\n');
                    const seatInfo = cells[3].textContent.trim().split('\n');
                    
                    const rowData = [
                        ticketNumber,
                        passengerInfo[0] || '',
                        passengerInfo[1] || '',
                        trainInfo[0] || '',
                        trainInfo[1] ? trainInfo[1].split(' → ')[0] : '',
                        trainInfo[1] ? trainInfo[1].split(' → ')[1] : '',
                        seatInfo[0] || '',
                        seatInfo[1] || '',
                        cells[4].textContent.trim(),
                        cells[5].textContent.trim(),
                        cells[6].textContent.trim()
                    ];
                    csv += rowData.join(',') + '\n';
                }
            });
            
            return csv;
        }

        function downloadCSV(content, filename) {
            const blob = new Blob(['\ufeff' + content], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // 更新分页
        function updatePagination() {
            const pagination = document.getElementById('pagination');
            let paginationHTML = '';

            // 上一页
            paginationHTML += `
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadTickets(${currentPage - 1})" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
            `;

            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage || i === 1 || i === totalPages || (i >= currentPage - 1 && i <= currentPage + 1)) {
                    paginationHTML += `
                        <li class="page-item ${i === currentPage ? 'active' : ''}">
                            <a class="page-link" href="#" onclick="loadTickets(${i})">${i}</a>
                        </li>
                    `;
                } else if (i === currentPage - 2 || i === currentPage + 2) {
                    paginationHTML += '<li class="page-item disabled"><a class="page-link">...</a></li>';
                }
            }

            // 下一页
            paginationHTML += `
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadTickets(${currentPage + 1})" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            `;

            pagination.innerHTML = paginationHTML;
        }

        // 显示加载状态
        function showLoading(show) {
            document.getElementById('loadingSpinner').style.display = show ? 'block' : 'none';
        }

        // 格式化日期时间
        function formatDateTime(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }

        // 显示提示信息
        function showAlert(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
            alertDiv.style.top = '20px';
            alertDiv.style.right = '20px';
            alertDiv.style.zIndex = '9999';
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(alertDiv);
            
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.parentNode.removeChild(alertDiv);
                }
            }, 3000);
        }
    </script>
</body>
</html>
